package com.deep.test.thread.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * <p>Description:安全的终止线程1、interrupt()2、volatile boolean on = true;</p>
 * Created with IDEA
 * author:hudepin
 * createTime:2018/7/5 16:05
 */
public class ShutDown {
    public static void main(String[] args) throws InterruptedException {
        Runner r1 = new Runner();
        Thread t1 = new Thread(r1,"runner1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        t1.interrupt();
        Runner r2 = new Runner();
        Thread t2 = new Thread(r2,"runner2");
        t2.start();
        SleepUtils.sleep(2);
        r2.cancel();
    }
    static class Runner implements Runnable{
        private int count;
        private volatile boolean on = true;
        public  void cancel(){
            on = false;
        }
        @Override
        public void run() {
            while(on && !Thread.currentThread().isInterrupted()){
                count++;
            }
            System.out.println(Thread.currentThread().getName()+",count:"+count);
        }
    }
}
